<?php
/**
 * LdapClient
 */

namespace Ldap;

/**
 * Class LdapClient
 * @package Ldap
 */
class LdapClient
{
    /**
     * Host of LDAP server.
     *
     * @var string
     */
    protected $host;

    /**
     * Port of LDAP server.
     *
     * @var int
     */
    protected $port;

    /**
     * Base distinguished name.
     *
     * @var string
     */
    protected $baseDN;

    /**
     * LDAP connection resource.
     *
     * @var resource
     */
    protected $ds;

    /**
     * Create LDAP connection.
     *
     * @param array $config
     *   Connection configuration.
     *
     * @throws LdapException
     */
    public function __construct(array $config)
    {
        if (!isset($config['host'])) {
            throw new LdapException("host not specified.");
        }
        if (empty($config['baseDN'])) {
            throw new LdapException("baseDN not specified.");
        }

        $this->host = $config['host'];
        if (strlen($this->host) > 8 && substr($this->host, 0, 8) == 'ldaps://') {
            $defaultPort = 636;
        } else {
            $defaultPort = 389;
        }
        $this->port = isset($config['port']) ? $config['port'] : $defaultPort;
        $this->ds = ldap_connect($this->host, $this->port);
        if (!$this->ds) {
            $this->ds = null;
            throw new LdapException("Could not connect to {$this->host}:{$this->port}", -1);
        }
        $this->baseDN = $config['baseDN'];
    }

    /**
     * Auto disconnect on destruct.
     */
    public function __destruct()
    {
        if (isset($this->ds)) {
            ldap_close($this->ds);
        }
    }
}